package com.smartmap;

import java.util.LinkedHashSet;

import org.apache.commons.lang3.StringUtils;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.andreabaccega.widget.FormEditText;
import com.smartmap.chat.ChatActivity;

public class LoginActivity extends BasicActivity {
	private ImageView topImage;
	private FormEditText nickNameText, pwdText;
	private ImageButton registerButton, loginButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		setViews();
		setButtonEvents();
	}

	private void setViews() {
		topImage = (ImageView) findViewById(R.id.topImage);
		topImage.setBackgroundResource(R.drawable.top_login);
		nickNameText = (FormEditText) findViewById(R.id.login_nickName);
		pwdText = (FormEditText) findViewById(R.id.login_pwd);
		loginButton = (ImageButton) findViewById(R.id.login_login_btn);
		registerButton = (ImageButton) findViewById(R.id.login_register_btn);
	}

	private void setButtonEvents() {
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (nickNameText.testValidity() && pwdText.testValidity()) {
					store(nickNameText.getText().toString(), pwdText
							.getEditableText().toString());
					Toast.makeText(LoginActivity.this, "登录成功", 2000).show();
					JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
					LinkedHashSet<String> set = new LinkedHashSet<String>();
					set.add("smartmap开发组");
					JPushInterface.setAliasAndTags(LoginActivity.this,
							sharedPreferencesUtils.getMemberId(), set);
					JPushInterface.init(LoginActivity.this); // 初始化 JPush
					Intent intent = new Intent(LoginActivity.this,
							ChatActivity.class);
					startActivity(intent);

				}
			}
		});
		registerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LoginActivity.this,
						RegisterActivity.class);
				startActivity(intent);
			}
		});
	}

	private void store(String nickName, String pwd) {
		sharedPreferencesUtils.setNickName(nickName);
		sharedPreferencesUtils.setPwd(pwd);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (ifRegister()) {
			nickNameText.setText(sharedPreferencesUtils.getNickName());
			pwdText.setText(sharedPreferencesUtils.getPwd());
			Toast.makeText(this, sharedPreferencesUtils.getEmail(), 2000)
					.show();
		}
	}

	private boolean ifRegister() {
		if (StringUtils.isEmpty(sharedPreferencesUtils.getNickName())) {
			return false;
		}
		return true;
	}
}
